<template>
  <el-dialog
    v-model="dialogVisible"
    title="许可证审批"
    width="900px"
    @close="handleClose"
  >
    <div v-if="approvalData" class="approval-content">
      <!-- 基本信息 -->
      <el-card class="info-card">
        <template #header>
          <span>基本信息</span>
        </template>
        <el-row :gutter="20">
          <el-col :span="8">
            <div class="info-item">
              <label>许可证编号：</label>
              <span>{{ approvalData.permitNumber }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="info-item">
              <label>作业类型：</label>
              <el-tag :type="getWorkTypeTagType(approvalData.workType)">
                {{ getWorkTypeLabel(approvalData.workType) }}
              </el-tag>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="info-item">
              <label>申请人：</label>
              <span>{{ approvalData.applicant }}</span>
            </div>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="info-item">
              <label>作业地点：</label>
              <span>{{ approvalData.location }}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="info-item">
              <label>申请部门：</label>
              <span>{{ approvalData.department }}</span>
            </div>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="info-item">
              <label>计划开始时间：</label>
              <span>{{ approvalData.startTime }}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="info-item">
              <label>计划结束时间：</label>
              <span>{{ approvalData.endTime }}</span>
            </div>
          </el-col>
        </el-row>
        
        <div class="info-item">
          <label>作业内容：</label>
          <p>{{ approvalData.workContent }}</p>
        </div>
      </el-card>
      
      <!-- 安全措施 -->
      <el-card class="info-card">
        <template #header>
          <span>安全措施</span>
        </template>
        <div class="safety-measures">
          <el-tag
            v-for="measure in approvalData.safetyMeasures"
            :key="measure"
            style="margin-right: 8px; margin-bottom: 8px"
          >
            {{ measure }}
          </el-tag>
        </div>
      </el-card>
      
      <!-- 作业人员 -->
      <el-card class="info-card">
        <template #header>
          <span>作业人员</span>
        </template>
        <el-table :data="approvalData.personnel" size="small">
          <el-table-column prop="name" label="姓名" width="120" />
          <el-table-column prop="type" label="工种" width="120">
            <template #default="{ row }">
              <el-tag size="small">{{ getPersonnelTypeLabel(row.type) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="certificateExpiry" label="证书有效期" width="150" />
        </el-table>
      </el-card>
      
      <!-- 气测人员 -->
      <el-card class="info-card">
        <template #header>
          <span>气测人员</span>
        </template>
        <el-table :data="approvalData.gasDetectors" size="small">
          <el-table-column prop="name" label="姓名" width="120" />
          <el-table-column prop="role" label="角色" width="120">
            <template #default="{ row }">
              <el-tag size="small">{{ getRoleLabel(row.role) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="department" label="部门" width="120" />
        </el-table>
      </el-card>
      
      <!-- 审批意见 -->
      <el-card class="approval-card">
        <template #header>
          <span>审批意见</span>
        </template>
        <el-form :model="approvalForm" :rules="approvalRules" ref="approvalFormRef" label-width="100px">
          <el-form-item label="审批结果" prop="result">
            <el-radio-group v-model="approvalForm.result">
              <el-radio value="approved">批准</el-radio>
              <el-radio value="rejected">驳回</el-radio>
            </el-radio-group>
          </el-form-item>
          
          <el-form-item label="审批意见" prop="comment">
            <el-input
              v-model="approvalForm.comment"
              type="textarea"
              :rows="4"
              placeholder="请输入审批意见"
            />
          </el-form-item>
          
          <el-form-item v-if="approvalForm.result === 'rejected'" label="驳回原因" prop="rejectReason">
            <el-select v-model="approvalForm.rejectReason" placeholder="请选择驳回原因" style="width: 100%">
              <el-option label="安全措施不完善" value="safety_measures" />
              <el-option label="人员资质不符合要求" value="personnel_qualification" />
              <el-option label="作业时间安排不合理" value="time_arrangement" />
              <el-option label="作业地点存在安全隐患" value="location_safety" />
              <el-option label="其他原因" value="other" />
            </el-select>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
    
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="submitting">
        提交审批
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'

interface ApprovalData {
  id: number
  permitNumber: string
  workType: string
  location: string
  applicant: string
  department: string
  startTime: string
  endTime: string
  workContent: string
  safetyMeasures: string[]
  personnel: any[]
  gasDetectors: any[]
}

interface ApprovalForm {
  result: 'approved' | 'rejected' | ''
  comment: string
  rejectReason: string
}

interface Props {
  modelValue: boolean
  approvalData: ApprovalData | null
}

interface Emits {
  (e: 'update:modelValue', value: boolean): void
  (e: 'success'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const dialogVisible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

const approvalFormRef = ref<FormInstance>()
const submitting = ref(false)

const approvalForm = reactive<ApprovalForm>({
  result: '',
  comment: '',
  rejectReason: ''
})

const approvalRules: FormRules = {
  result: [
    { required: true, message: '请选择审批结果', trigger: 'change' }
  ],
  comment: [
    { required: true, message: '请输入审批意见', trigger: 'blur' }
  ],
  rejectReason: [
    { required: true, message: '请选择驳回原因', trigger: 'change' }
  ]
}

// 获取作业类型标签类型
const getWorkTypeTagType = (type: string) => {
  const typeMap: Record<string, string> = {
    high_altitude: 'warning',
    hot_work: 'danger',
    electrical: 'primary',
    confined_space: 'info',
    lifting: 'success'
  }
  return typeMap[type] || 'info'
}

// 获取作业类型标签
const getWorkTypeLabel = (type: string) => {
  const labelMap: Record<string, string> = {
    high_altitude: '高空作业',
    hot_work: '动火作业',
    electrical: '电气作业',
    confined_space: '受限空间',
    lifting: '起重作业'
  }
  return labelMap[type] || type
}

// 获取人员类型标签
const getPersonnelTypeLabel = (type: string) => {
  const labelMap: Record<string, string> = {
    electrician: '电工',
    welder: '焊工',
    crane_operator: '起重工',
    high_altitude: '高空作业'
  }
  return labelMap[type] || type
}

// 获取角色标签
const getRoleLabel = (role: string) => {
  const labelMap: Record<string, string> = {
    gas_detector: '气测员',
    safety_officer: '安全员'
  }
  return labelMap[role] || role
}

// 提交审批
const handleSubmit = async () => {
  if (!approvalFormRef.value) return
  
  try {
    await approvalFormRef.value.validate()
    submitting.value = true
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 2000))
    
    const result = approvalForm.result === 'approved' ? '批准' : '驳回'
    ElMessage.success(`审批${result}成功`)
    
    emit('success')
    handleClose()
  } catch (error: any) {
    ElMessage.error(error.message || '审批失败')
  } finally {
    submitting.value = false
  }
}

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false
  approvalForm.result = ''
  approvalForm.comment = ''
  approvalForm.rejectReason = ''
  approvalFormRef.value?.resetFields()
}

// 监听对话框显示状态
watch(dialogVisible, (visible) => {
  if (!visible) {
    handleClose()
  }
})
</script>

<style lang="scss" scoped>
.approval-content {
  .info-card {
    margin-bottom: 20px;
    
    .info-item {
      margin-bottom: 12px;
      
      label {
        font-weight: 500;
        color: #333;
        margin-right: 8px;
      }
      
      p {
        margin: 8px 0 0 0;
        color: #666;
        line-height: 1.5;
      }
    }
  }
  
  .safety-measures {
    min-height: 40px;
  }
  
  .approval-card {
    .el-form-item {
      margin-bottom: 20px;
    }
  }
}
</style>

